package com.codinghero.example.longleg;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.codinghero.util.FileUtils;
import com.codinghero.util.ImageUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GetHuaBanPic {

	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient();
		try {
			for(int i=1; i<=15; i++){
				HttpGet httpget = new HttpGet("http://huaban.com/search/?q=%E5%BD%AD%E4%B9%85%E6%B4%8B&hiyielg9&page="+i+"&per_page=20&wfl=1");
	
				System.out.println("executing request " + httpget.getURI());
				httpget.setHeader("X-Request", "JSON");
				httpget.setHeader("X-Requested-With", "XMLHttpRequest");
	
				// Create a response handler
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String responseBody = httpclient.execute(httpget, responseHandler);
				System.out.println("----------------------------------------");
				System.out.println(responseBody);
				System.out.println("----------------------------------------");
	
				Gson gson = new Gson();
				Map<String, ?> retMap = gson.fromJson(responseBody,
						new TypeToken<Map<String, Object>>() {
						}.getType());
				List<?> pins = (List<?>) retMap.get("pins");
				for (Object pin : pins) {
					Map<String, ?> file = (Map<String, ?>) ((Map<String, ?>)pin).get("file");
					String rawText = (String) ((Map<String, ?>)pin).get("raw_text");
					String imageUrl = "http://img.hb.aicdn.com/" + file.get("key");
					BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));
					
					String destPath = "F:\\girleg\\orig\\" + file.get("key") + ".jpg";
					ImageIO.write(bufferedImage, "jpg", new File(destPath));
					Map<String, Integer> size = ImageUtils.getSize(new File(destPath));
					if (size.get("height") < 600 && size.get("width") < 600)
						FileUtils.deleteFile(destPath);
				}
			}
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
	}

}
